<template>
  <a-modal
    :open="open"
    :title="formTitle"
    :confirm-loading="loading"
    :ok-text="$t('common.submit')"
    :cancel-text="$t('common.cancel')"
    @ok="handleSubmit"
    @cancel="updateOpen(false)"
    width="700px"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item name="parentId" :label="$t('menu.parentMenu')">
        <a-tree-select
          v-model:value="form.parentId"
          :tree-data="parentTreeData"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          :fieldNames="{ label: 'name', value: 'id', children: 'children' }"
          :placeholder="$t('menu.selectParent')"
          tree-default-expand-all
          allow-clear
        />
      </a-form-item>
      <a-form-item name="type" :label="$t('menu.type')">
        <a-radio-group v-model:value="form.type" @change="handleTypeChange">
          <a-radio :value="MenuType.DIRECTORY">{{ $t('menu.directory') }}</a-radio>
          <a-radio :value="MenuType.MENU">{{ $t('menu.menu') }}</a-radio>
          <a-radio :value="MenuType.BUTTON">{{ $t('menu.button') }}</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item name="name" :label="$t('menu.name')">
        <a-input v-model:value="form.name" :placeholder="$t('menu.namePlaceholder')" />
      </a-form-item>
      
      <template v-if="!isMenuType(form.type, MenuType.BUTTON)">
        <a-form-item name="icon" :label="$t('menu.icon')">
          <a-input v-model:value="form.icon" :placeholder="$t('menu.iconPlaceholder')">
            <template #prefix>
              <component :is="getIconComponent(form.icon)" />
            </template>
            <template #addonAfter>
              <a @click="handleSelectIcon">{{ $t('menu.selectIcon') }}</a>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item name="path" :label="$t('menu.path')">
          <a-input v-model:value="form.path" :placeholder="$t('menu.pathPlaceholder')" />
        </a-form-item>
        <a-form-item name="isExternal" :label="$t('menu.isExternal')" v-if="isMenuType(form.type, MenuType.MENU)">
          <a-switch v-model:checked="form.isExternal" />
        </a-form-item>
      </template>
      
      <template v-if="isMenuType(form.type, MenuType.MENU)">
        <a-form-item name="component" :label="$t('menu.component')">
          <a-input v-model:value="form.component" :placeholder="$t('menu.componentPlaceholder')" />
        </a-form-item>
        <a-form-item name="isCache" :label="$t('menu.isCache')">
          <a-switch v-model:checked="form.isCache" />
        </a-form-item>
      </template>
      
      <template v-if="!isMenuType(form.type, MenuType.DIRECTORY)">
        <a-form-item name="permission" :label="$t('menu.permission')">
          <a-input v-model:value="form.permission" :placeholder="$t('menu.permissionPlaceholder')" />
        </a-form-item>
      </template>
      
      <a-form-item name="isVisible" :label="$t('menu.isVisible')" v-if="!isMenuType(form.type, MenuType.BUTTON)">
        <a-switch v-model:checked="form.isVisible" />
      </a-form-item>
      <a-form-item name="status" :label="$t('menu.status')">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="1">{{ $t('common.enabled') }}</a-radio>
          <a-radio :value="0">{{ $t('common.disabled') }}</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item name="orderNum" :label="$t('menu.orderNum')">
        <a-input-number v-model:value="form.orderNum" :min="0" :max="999" style="width: 100%" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import type { FormInstance } from 'ant-design-vue'
import type { Menu, CreateMenu } from '@/types/api/system/menu'
import { MenuType } from '@/types/api/system/menu'
import { useFormRules } from '../config/formRules'
import { MenuOutlined } from '@ant-design/icons-vue'

// 组件名称
defineOptions({
  name: 'MenuFormModal'
})

// Props定义
const props = withDefaults(defineProps<{
  open: boolean
  loading?: boolean
  form: CreateMenu
  formTitle: string
  parentTreeData: Menu[]
}>(), {
  loading: false,
  parentTreeData: () => []
})

// Emits定义
const emit = defineEmits<{
  (e: 'update:open', value: boolean): void
  (e: 'select-icon'): void
  (e: 'submit'): void
  (e: 'update:form', form: CreateMenu): void
}>()

// 表单引用
const formRef = ref<FormInstance>()
const formRules = useFormRules(props.form)

// 更新open状态
const updateOpen = (value: boolean) => {
  emit('update:open', value)
}

/**
 * 提交表单处理
 */
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    emit('submit')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

/**
 * 选择图标处理
 */
const handleSelectIcon = () => {
  emit('select-icon')
}

/**
 * 菜单类型变更处理
 */
const handleTypeChange = () => {
  const updatedForm = { ...props.form }
  
  if (updatedForm.type === MenuType.DIRECTORY) {
    updatedForm.component = ''
    updatedForm.permission = ''
  } else if (updatedForm.type === MenuType.BUTTON) {
    updatedForm.path = ''
    updatedForm.component = ''
    updatedForm.icon = ''
    updatedForm.isExternal = false
    updatedForm.isCache = false
    updatedForm.isVisible = true
  }
  
  emit('update:form', updatedForm)
}

/**
 * 判断菜单类型
 * @param type 菜单类型
 * @param targetType 目标类型
 * @returns 是否匹配
 */
const isMenuType = (type: MenuType | undefined, targetType: MenuType): boolean => {
  if (!type) {
    return false
  }
  return type === targetType
}

/**
 * 获取图标组件
 * @param iconName 图标名称
 * @returns 图标组件
 */
const getIconComponent = (iconName?: string) => {
  if (!iconName) return MenuOutlined
  return MenuOutlined
}

// 监听弹窗关闭
watch(() => props.open, (val) => {
  if (!val) {
    formRef.value?.resetFields()
  }
})

// 导出表单实例
defineExpose({
  formRef
})
</script>

<style scoped>
/* 无需额外样式 */
</style> 